package com.example.demo.web;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author admin
 * 分布式文件上传
 */
@Slf4j
@Api(tags = "Minio管理")
@RestController
@RequestMapping("/minio")
public class MinioController {

    @PostMapping("/upload")
    @ApiOperation(value = "minio上传测试")
    public void upload(MultipartFile file) {
        InputStream inputStream = null;
        // 创建Minio的连接对象
        MinioClient minioClient = getClient();
        // 桶对象
        String bucketName = "testbucket";
        try {
            inputStream = file.getInputStream();
            // 基于官网的内容，判断文件存储的桶是否存在 如果桶不存在就创建桶
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (exists) {
                System.out.println("该桶已经存在");
            } else {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            // 操作文件
            String fileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/")
                    .format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
                    .bucket(bucketName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1).build();
            minioClient.putObject(objectArgs);

            log.info("url:{}", "http://127.0.0.1:9000/" + bucketName + "/"+fileName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传失败");
        } finally {
            // 防止内存泄漏
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.debug("inputStream close IOException:" + e.getMessage());
                }
            }
        }
    }

    /**
     * minio连接
     *
     * @return Minio连接
     */
    private MinioClient getClient() {
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint("http://127.0.0.1:9000")
                        .credentials("minioadmin", "minioadmin")
                        .build();
        return minioClient;
    }


}